#include "stm8l15x.h"
#include "stm8l15x_exti.h"
#include "LCD_Configuration.h"
#include "LCD_RTC.h"


#define MAIN_KEY_UNLOCK			0
#define MAIN_KEY_LOCK				1

u8 g_wakeup_count = 0;
u8 g_battery_life = 0;

void GPIO_Setup(void)
{
	GPIO_Init(GPIOG,GPIO_Pin_2,GPIO_Mode_Out_PP_High_Fast);
	GPIO_Init(GPIOF,GPIO_Pin_4,GPIO_Mode_In_PU_IT);
	GPIO_Init(GPIOF,GPIO_Pin_5,GPIO_Mode_In_PU_IT);
	EXTI_SetPortSensitivity(EXTI_Port_F, EXTI_Trigger_Falling);
	EXTI_SelectPort(EXTI_Port_F);
	EXTI_SetHalfPortSelection(EXTI_HalfPort_F_MSB, ENABLE);
}

void SYS_CLK_Configuration(void) 
{
  CLK_SYSCLKDivConfig(CLK_SYSCLKDiv_1);//div 1
  CLK_SYSCLKSourceSwitchCmd(ENABLE); 
  CLK_SYSCLKSourceConfig(CLK_SYSCLKSource_LSE); //32.768K
  
  while (CLK_GetSYSCLKSource() != CLK_SYSCLKSource_LSE);

  CLK_HSICmd(DISABLE);
}

void wait_main_key_up(void)
{
	g_wakeup_count = 0;
	while(!KEY_MAIN) {
		if(g_wakeup_count > 1) {
			break;
		}
	}
}

void main(void)
{
	uint8_t key_main_lock = MAIN_KEY_UNLOCK;
	uint8_t key_mem_press_cnt = 0;
	uint8_t last_wakeup_count = g_wakeup_count;

	GPIO_Setup();
	LCD_Configuration(); 
	RTC_Clock_Init();

	SYS_CLK_Configuration();
	enableInterrupts();
 
	while (1) {
		Time_Show();

		if(!KEY_MEM) {
			if(key_mem_press_cnt++ > 2) {
				RTC_Setting();
				init_RTC_last_data();
				RTC_WakeUp_time(RTC_WakeUp_Time_1000ms);
				clear_big();
				key_mem_press_cnt = 0;
				continue;
			}
		} else {
			key_mem_press_cnt = 0;
		}

		if((!KEY_MAIN) && (key_main_lock == MAIN_KEY_UNLOCK)) {
			key_main_lock = MAIN_KEY_LOCK;
			if(LED_IS_ON()) {
				LED_OFF();
			} else {
				LED_ON();
			}
			wait_main_key_up();
			last_wakeup_count = g_wakeup_count;
		} else {
			if(LED_IS_ON()) {
				if(g_wakeup_count - last_wakeup_count >= 3) {
					LED_OFF();
				}
			}
			key_main_lock = MAIN_KEY_UNLOCK;
			halt();
		}
	}
}


